Chapter 20: Pandas
From book
Python Programming (Problem solving, Packages and Libraries)
Published by McGraw Hill Education (India) Private limited.
By:
This is Part 2 of the html document on Chapter 20 Pandas
This Assignment/ Project is given on page2 537-546 of the book
(Note:- Categorical means that the data is a category or name of and so not numeric.)
# Load .tsv file in a DataFrame object and see its shape
import pandas as pd
path2file = r'C:\temp_data\drugsComTrain_raw.tsv' # Use your file path instead
# Read the data into a pandas DataFrame object
my_df = pd.read_csv(path2file, sep = '\t', error_bad_lines=False)
# Get shape of data as a tuple
print(my_df.shape)
#To get rows
print('rows->', my_df.shape[0])
# To get columns
print('columns->', my_df.shape[1])
# To get names of all the columns
print(my_df.columns)
# Lets rename the first column which is unnamed
my_df.columns.values[0] = 'someNumber'
# Get 1 row along with column names but as a transpose (Use T)
# When you use T, the column names are shown as rows
print(my_df.head(1).T)
# Lets get the index of the data ie number of rows in the DataSet object
print(my_df.index)
# Lets get the data types for each column
print(my_df.dtypes)
# Suppose you want only first 5 drug names
print(my_df['drugName'].head(5))
# How many unique drugs are there?
print(my_df.drugName.nunique())
# Which are the 5 most common drugs?
my_df.drugName.value_counts().head(5) # value_counts() note pulural in value_counts()
You can see the complete signature of the describe() method at:- http://pandas.pydata.org/pandas-docs/version/0.17/generated/pandas.DataFrame.describe.html
# Describe the drugs data
# Default is to provide a summary for the numerical columns only.
# include = 'all' gives summary of all the columns
my_df.describe(include = 'all')
# But by default describe() gives summary of numeric columns only
my_df.describe()
# include='object' gives summary of character columns
my_df.describe(include=['object'])
# If you want to get summary of a particular column say drugName
my_df.drugName.describe()
# Get oldest and latest dates
oldest_date = min(my_df['date'])
print('oldest date->', oldest_date)
latest_date = max(my_df['date'])
print('latest date->', latest_date)
# Count number of NaN or null
my_df.isnull().sum()
# Clean the data
# drop NaNs in the 'condition' column and update the dataframe
my_df.dropna(subset = ['condition'], inplace = True)
# Check that the NaN are removed
my_df.isnull().sum()
# We want to see how many reviews were there in each year.
# The date column is of data type 'object' and has day, month and year.
# We only want the year part
# First change date column from object to datetime format
my_df['date'] = pd.to_datetime(arg = my_df['date'])
# Pick up only the year part of the date
# df_drugs is a new DataFrame object created from my_df
df_drugs = pd.DataFrame(my_df['date'].groupby(my_df.date.dt.year).agg('count'))
# Rename the column of new dataFrame object to 'Count'
df_drugs.columns = ['Count']
# Rename index of new DataFrame object ie df_drugs to 'Year'
df_drugs.index.names = ['Year']
# Check that we got total review count for each year
print(df_drugs)
import matplotlib.pyplot as plt
plt.style.use(['seaborn'])
ax = df_drugs.plot(kind = 'bar')
x_labels = df_drugs.index
ax.set_xticklabels(x_labels)
# Get name of index and set x-label to name of index
xlabel = df_drugs.index.name
ax.set_xlabel(xlabel)
ax.set_ylabel('Review_Count')
ax.set_title('Reviews per Year')
plt.show()
(If you dont have or are not using Jupyter notebook, you may copy and paste the code below and it should run.)
Off course you must:-
- Have pandas and matplotlib libraries installed
- Download the data set and
- Give the path to the place where you have stored the downloaded files.
# The entire code in one place
import pandas as pd
path2file = r'C:\temp_data\drugsComTrain_raw.tsv' # Use your file path instead
# Read the data into a pandas DataFrame object
my_df = pd.read_csv(path2file, sep = '\t', error_bad_lines=False)
# Get shape of data as a tuple
print(my_df.shape)
#To get rows
print('rows->', my_df.shape[0])
# To get columns
print('columns->', my_df.shape[1])
# To get names of all the columns
print(my_df.columns)
# Lets rename the first column which is unnamed
my_df.columns.values[0] = 'someNumber'
# Get 1 row along with column names but as a transpose (Use T)
# When you use T, the column names are shown as rows
print(my_df.head(1).T)
# Lets get the index of the data ie number of rows in the DataSet object
print(my_df.index)
# Lets get the data types for each column
print(my_df.dtypes)
# Suppose you want only first 5 drug names
print(my_df['drugName'].head(5))
# How many unique drugs are there?
print(my_df.drugName.nunique())
# Which are the 5 most common drugs?
my_df.drugName.value_counts().head(5) # value_counts() note pulural in value_counts()
# Describe the drugs data
# Default is to provide a summary for the numerical columns only.
# include = 'all' gives summary of all the columns
my_df.describe(include = 'all')
# But by default describe() gives summary of numeric columns only
my_df.describe()
# include='object' gives summary of character columns
my_df.describe(include=['object'])
# If you want to get summary of a particular column say drugName
my_df.drugName.describe()
# Get oldest and latest dates
oldest_date = min(my_df['date'])
print('oldest date->', oldest_date)
latest_date = max(my_df['date'])
print('latest date->', latest_date)
# Count number of NaN or null
my_df.isnull().sum()
# Clean the data
# drop NaNs in the 'condition' column and update the dataframe
my_df.dropna(subset = ['condition'], inplace = True)
# Check that the NaN are removed
my_df.isnull().sum()
# We want to see how many reviews were there in each year.
# The date column is of data type 'object' and has day, month and year.
# We only want the year part
# First change date column from object to datetime format
my_df['date'] = pd.to_datetime(arg = my_df['date'])
# Pick up only the year part of the date
# df_drugs is a
df_drugs = pd.DataFrame(my_df['date'].groupby(my_df.date.dt.year).agg('count'))
# Rename the column of new dataFrame object to 'Count'
df_drugs.columns = ['Count']
# Rename index of DataFrame to 'Year'
df_drugs.index.names = ['Year']
# Check that we got total review count for each year
print(df_drugs)
import matplotlib.pyplot as plt
plt.style.use(['seaborn'])
ax = df_drugs.plot(kind = 'bar')
x_labels = df_drugs.index
ax.set_xticklabels(x_labels)
# Get name of index and set x-label to name of index
xlabel = df_drugs.index.name
ax.set_xlabel(xlabel)
ax.set_ylabel('Count')
ax.set_title('Reviews per Year')
plt.show()